<template>
    <div>
        <Header>
            <template #right>
                <div class="flex items-center bg-[#fafbfc] rounded-[1.5rem] h-[3rem] w-[17.5rem] py-[1rem] px-[2rem] relative">
                    <input 
                        v-model="keyword" 
                        type="text" 
                        placeholder="搜索帖子、用户、标签..."
                        class="flex-1 border-none outline-none bg-transparent text-[1rem] text-[#9CA3AF] placeholder:text-[#9CA3AF] placeholder:text-[1rem]"
                        @input="handleInput"
                        @keyup.enter="onSearch"
                        @focus="showSuggestions = true"
                        @blur="hideSuggestionsDelayed"
                    />
                    <img 
                        src="/icon/search.png" 
                        class="w-[1rem] h-[1rem] cursor-pointer ml-2" 
                        @click="onSearch" 
                    />
                    
                    <!-- 搜索建议下拉菜单 -->
                    <div 
                        v-if="showSuggestions && suggestions.length > 0" 
                        class="absolute top-[3.25rem] left-0 w-full bg-white rounded-[0.5rem] shadow-md z-10 max-h-[20rem] overflow-y-auto"
                    >
                        <div 
                            v-for="(suggestion, index) in suggestions" 
                            :key="index"
                            class="px-[1rem] py-[0.75rem] hover:bg-[#F9FAFB] cursor-pointer text-[0.875rem] border-b border-[#F3F4F6] last:border-b-0"
                            @mousedown.prevent="selectSuggestion(suggestion)"
                        >
                            <div class="flex items-center">
                                <!-- <img 
                                    v-if="suggestion.type === 'post'" 
                                    src="/icon/post.png" 
                                    class="w-[1rem] h-[1rem] mr-[0.5rem]"
                                    alt="帖子"
                                />
                                <img 
                                    v-else-if="suggestion.type === 'user'" 
                                    src="/icon/user.png" 
                                    class="w-[1rem] h-[1rem] mr-[0.5rem]"
                                    alt="用户"
                                />
                                <img 
                                    v-else-if="suggestion.type === 'tag'" 
                                    src="/icon/tag.png" 
                                    class="w-[1rem] h-[1rem] mr-[0.5rem]"
                                    alt="标签"
                                /> -->
                                <span>{{ suggestion.text }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </Header>

        <div class="flex w-[80rem] mx-auto gap-[1.5rem] pb-[4rem]">
            <!-- 侧边栏 -->
            <div class="w-[10rem]" :class="{'pt-[3.3rem]': userStore.isLogin()}">
                <!-- 分类 -->
                <Category></Category>
            </div>
            <!-- 内容 -->
            <div class="w-[48.5rem]">
                <!-- 活动公告 -->
                <!-- <EventAnnouncements></EventAnnouncements> -->

                <!-- 发表主题 -->
                <!-- v-if="userStore.isLogin()" -->
                <PublishTopic ></PublishTopic>
                
                <!-- 列表 -->
                 <List></List>
            </div>
            <!-- 右边栏目 -->
            <div class="w-[20rem] gap-[1.5rem] flex flex-col " :class="{'pt-[3.3rem]': userStore.isLogin()}">
                <!-- 社区数据 -->
                <!-- <CommunityData></CommunityData> -->

                <!-- 优质作者 -->
                <ActiveAuthor></ActiveAuthor>

                <!-- 热门文章 -->
                <PopularArticles></PopularArticles>

                <!-- 成长体系 -->
                <!-- <GrowthSystem></GrowthSystem> -->

                <!-- 成就徽章 -->
                <!-- <AchievementBadges></AchievementBadges> -->
            </div>
        </div>
        <!-- 底部 -->
        <Footer mode="dark"></Footer>
    </div>
</template>
<script setup lang="ts">
import Header from '@/components/Header/index.vue'
import Category from './components/Category.vue'
import PublishTopic from './components/PublishTopic.vue'
import CommunityData from './components/CommunityData.vue'
import ActiveAuthor from './components/ActiveAuthor.vue'
import PopularArticles from './components/PopularArticles.vue'
import GrowthSystem from './components/GrowthSystem.vue'
import AchievementBadges from './components/AchievementBadges.vue'
import EventAnnouncements from './components/EventAnnouncements.vue'
import List from './components/List.vue'
import Footer from '@/components/Footer/index.vue'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

// 定义类型接口
interface Suggestion {
  id: number;
  text: string;
  type: 'post' | 'user' | 'tag';
}

const router = useRouter()
const userStore = useUserStore()
const keyword = ref('')
const showSuggestions = ref(false)
const suggestions = ref<Suggestion[]>([])
let debounceTimer: number | null = null
let blurTimer: number | null = null

// 模拟API，实际开发中替换为真实API调用
const mockSuggestions = (query: string): Suggestion[] => {
  if (!query) return []
  
  const mockData: Suggestion[] = [
    { id: 1, text: `前端${query}学习指南`, type: 'post' },
    { id: 2, text: `如何掌握${query}技巧`, type: 'post' },
    { id: 3, text: `${query}精选`, type: 'tag' },
    { id: 4, text: `${query}专家`, type: 'user' },
    { id: 5, text: `${query}问题解决方案`, type: 'post' },
  ]
  
  return mockData.filter(item => 
    item.text.toLowerCase().includes(query.toLowerCase())
  )
}

// 实现防抖的输入处理
const handleInput = () => {
  // 清除之前的定时器
  if (debounceTimer) {
    clearTimeout(debounceTimer)
  }
  
  // 设置新的定时器，300ms后执行搜索
  debounceTimer = window.setTimeout(() => {
    if (keyword.value.trim()) {
      suggestions.value = mockSuggestions(keyword.value)
    } else {
      suggestions.value = []
    }
  }, 300)
}

const onSearch = () => {
  if (!keyword.value.trim()) return
  
  // 清空建议并跳转到搜索结果页面
  suggestions.value = []
  showSuggestions.value = false
  
  // 跳转到搜索结果页
  router.push(`/forum/search?keyword=${encodeURIComponent(keyword.value)}`)
}

const hideSuggestionsDelayed = () => {
  // 延迟隐藏下拉菜单，让点击事件有时间触发
  blurTimer = window.setTimeout(() => {
    showSuggestions.value = false
  }, 200)
}

const selectSuggestion = (suggestion: Suggestion) => {
  // 根据类型执行不同的操作
  switch (suggestion.type) {
    case 'post':
      console.log('跳转到帖子:', suggestion.id)
      router.push(`/forum/details/${suggestion.id}`)
      break
    case 'user':
      console.log('跳转到用户页面:', suggestion.id)
      router.push(`/user/${suggestion.id}`)
      break
    case 'tag':
      console.log('搜索标签:', suggestion.text)
      router.push(`/forum/search?tag=${encodeURIComponent(suggestion.text)}`)
      break
  }
  
  // 关闭建议下拉框
  showSuggestions.value = false
}

// 组件销毁前清除所有定时器
onBeforeUnmount(() => {
  if (debounceTimer) {
    clearTimeout(debounceTimer)
}
  if (blurTimer) {
    clearTimeout(blurTimer)
  }
})
</script>
<style scoped lang="scss"></style>